package com.stmt.stmtdesktop.udp;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.Getter;

/**
 * $0123456789ABCDEF<001><1001><123456789012345><100>
 *
 * @author liangbo
 */

public class DeviceInsDTO {

  //$1-6<?><?><?><?><?><?>
  private final String body;
  private final List<String> params;
  @Getter
  private final TcpIpType tcpIpType;

  @Getter
  private final DeviceEnum.DeviceInstruct instruction;

  public DeviceInsDTO(String body, TcpIpType tcpIpType) {
    this.tcpIpType = tcpIpType;
    this.body = body;
    if (body != null) {
      String macno = body.substring(1, body.indexOf('<'));
      params = new ArrayList<>();
      params.add(macno);

      Pattern p2 = Pattern.compile("(?<=<)[^>]+");
      Matcher m2 = p2.matcher(body);
      while (m2.find()) {
        params.add(m2.group());
      }
      this.instruction = Arrays.stream(DeviceEnum.DeviceInstruct.values())
          .filter(it -> Objects.equals(it.getCode(), params.get(2)))
          .findAny()
          .orElse(null);
    } else {
      params = new ArrayList<>();
      instruction = null;
    }
  }

  public enum TcpIpType {
    /**
     * 协议类型
     */
    TCP(1), UDP(0);
    @Getter
    private final Integer code;

    TcpIpType(Integer code) {
      this.code = code;
    }
  }

  public boolean isOk() {
    return Objects.equals(getParam(3).toUpperCase(), "OK");
  }


  public String body() {
    return body;
  }

  public List<String> queryParams() {
    return params;
  }

  public String getMacno() {
    return params.get(0);
  }

  public String getFrame() {
    return params.get(1);
  }


  public String getParam(int index) {
    return params.get(index);
  }
}
